package com.admins.service.impl;

import com.commons.utils.MD5Tools;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.admins.dao.AdminDao;
import com.admins.dto.AdminLoginDto;
import com.admins.entity.Users;
import com.admins.service.AdminService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import javax.annotation.Resource;
import java.util.List;
import java.util.concurrent.TimeUnit;

/**
 * @author mis_wu
 * @date 2021/11/29 16:07
 */
@Service
@Transactional(rollbackFor = Exception.class)
public class AdminServiceImpl implements AdminService {
    @Resource
    private AdminDao adminDao;
    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 管理员登录
     * @param loginId
     * @return
     */
    @Override
    public AdminLoginDto adminLogin(String loginId) {
        return adminDao.adminLogin(loginId);
    }

    /**
     * 随机分配头像
     * @param admin
     */
    @Override
    public void savePic(AdminLoginDto admin) {
        adminDao.savePic(admin);
    }

    /**
     * 分页查询所有用户
     * @param page
     * @param size
     * @return
     */
    public PageInfo<Users> queryAllUsers(int page,int size) {
        PageHelper.startPage(page,size);
        //判断key是否存在
        if (redisTemplate.hasKey("usersList")){
            //List<Users> list=(List<Users>) redisTemplate.opsForList().leftPop("usersList");
            List<Users> list = (List<Users>) redisTemplate.opsForValue().get("userslist");
            return new PageInfo<Users>(list);
        }else {
            //右添加
            //redisTemplate.opsForList().rightPush("usersList", adminDao.queryAllUsers());
            redisTemplate.opsForValue().set("userslist",adminDao.queryAllUsers(),60,TimeUnit.MINUTES);
            //指定key的失效时间
            //redisTemplate.expire("usersList",60, TimeUnit.MINUTES);
            //根据key获取过期时间
            //Long expire = redisTemplate.getExpire("usersList");
            return new PageInfo<Users>(adminDao.queryAllUsers());
        }

    }

    /**
     * 编辑用户信息
     * @param users
     * @return
     */
    public int updateUserInfo(Users users) {
        return adminDao.updateUserInfo(users);
    }
}
